package cn.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//字符集过滤器，拦截所有的请求和响应
//@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
	private String encoding;
	private Boolean forceEncoding;

	// 构造方法
	public CharacterEncodingFilter() {
		System.out.println("CharacterEncodingFilter实例化");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 初始化
		System.out.println("CharacterEncodingFilter初始化");
		encoding = filterConfig.getInitParameter("encoding");
		System.out.println("encoding ===>" + encoding);
		forceEncoding = new Boolean(filterConfig.getInitParameter("forceEncoding"));
		System.out.println("forceEncoding ===>" + forceEncoding);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 执行过滤功能的方法
		System.out.println("CharacterEncodingFilter开始执行过滤功能");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		if ("UTF-8".equalsIgnoreCase(encoding) && forceEncoding) {
			req.setCharacterEncoding(encoding);
			rep.setCharacterEncoding(encoding);
		}
		// 对请求进行方行
		chain.doFilter(request, response);
		System.out.println("CharacterEncodingFilter执行过滤功能结束！");
	}

	@Override
	public void destroy() {
		// 销毁
		System.out.println("CharacterEncodingFilter销毁");
	}
}
